package logic

import (
	"context"
	"fmt"
	"strconv"
	"user/pkg"

	"user/models/cache"
	"user/models/mysql"

	"user/internal/svc"
	"user/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginUserLogic {
	return &LoginUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginUserLogic) LoginUser(in *user.LoginUserRequest) (*user.LoginUserResponse, error) {
	// todo: add your logic here and delete this line

	get := cache.Rdb.Get(l.ctx, "sendSms"+"login"+in.Mobile)
	if get.Val() != in.Sms {
		return nil, fmt.Errorf("短信验证码错误,请重新输入")
	}

	var users mysql.User
	mysql.DB.Debug().Where("account = ?", in.Mobile).Find(&users)
	if users.ID == 0 {
		users = mysql.User{
			Account:  in.Mobile,
			Password: pkg.Md5(in.Mobile),
		}
		mysql.DB.Create(&users)
	}

	return &user.LoginUserResponse{UserId: strconv.Itoa(int(users.ID))}, nil
}
